const path = require('path')
const config = require("./proxy.config")
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const TerserPlugin = require('terser-webpack-plugin');
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const CompressionPlugin = require('compression-webpack-plugin');

function resolve(dir) {
  return path.join(__dirname, dir)
}
const isPro = process.env.NODE_ENV === "production"
module.exports = {
  publicPath: isPro ? "/" : "/",
  devServer: {
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    open: true,
    hot: true,
    ...config,
  },
  productionSourceMap: false,
  configureWebpack: {
    plugins: isPro ? [
      new WorkboxWebpackPlugin.GenerateSW({
        clientsClaim: true, //这些选项帮助快速启用
        skipWaiting: true, //不允许遗留任何“旧的”
        runtimeCaching: [
          {
            urlPattern: /\.(?:png|jpg|jpeg|svg|js|css)$/,
            handler: "NetworkFirst",
          },
        ],
      }),
      new HardSourceWebpackPlugin(),
      new CompressionPlugin({
        test: /\.(js|css|png|jpg|jpeg|svg)(\?.*)?$/i, //需要压缩的文件正则
        threshold: 1024, //文件大小大于这个值时启用压缩
        deleteOriginalAssets: false //压缩后保留原文件
      })
    ] : [],
    optimization: isPro ? {
      runtimeChunk: "single",
      usedExports: true, //进行treeshaking
      sideEffects: true,
      minimize: true,
      minimizer: [
        new TerserPlugin({
          parallel: true, //多线程构建启用
          terserOptions: {
            compress: {
              drop_console: true, //移除所有console相关代码；
              drop_debugger: true, //移除自动断点功能；
              pure_funcs: ["console.log", "console.error"], //配置移除指定的指令，如console.log,alert等
            },
            format: {
              comments: false, //删除注释
            },
          },
          extractComments: false, //是否将注释剥离到单独的文件中
        }),
        new UglifyJSPlugin({
          parallel: true, //多线程构建启用
        }),
      ]
    } : {},
  },
  pluginOptions: {
    "style-resources-loader": {
      preProcessor: "less",
      patterns: [
        // 全局变量路径
        path.resolve(__dirname, "./src/theme/style.less"),
      ],
    },
  },
  chainWebpack: config => {
    config.plugins.delete('preload');
    config.plugins.delete('prefetch');
    config.module.rule("svg").exclude.add(resolve("src/assets/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: 'icon-[name]'
      })
      .end();
    config.optimization.splitChunks(isPro ? {
      chunks: "all",
      minSize: 500, // 生成 chunk 的最小体积（以 bytes 为单位）。 number = 20000 { [index: string]: number }
      // maxSize: 450000,
      minChunks: 1, // 拆分前必须共享模块的最小 chunks 数。
      maxAsyncRequests: 100, //按需加载时的最大并行请求数。
      maxInitialRequests: 100, // 入口点的最大并行请求数。
      enforceSizeThreshold: 50000, // 强制执行拆分的体积阈值和其他限制（minRemainingSize，maxAsyncRequests，maxInitialRequests）将被忽略。
      // cacheGroups: {
      //   libs: {
      //     name: 'chunk-libs',
      //     test: /[\\/]node_modules[\\/]/,
      //     priority: 10,
      //     chunks: 'initial' // only package third parties that are initially dependent
      //   },
      //   elementUI: {
      //     name: 'chunk-elementUI', // split elementUI into a single package
      //     priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
      //     test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
      //   },
      //   commons: {
      //     name: 'chunk-commons',
      //     test: resolve('src/components'), // can customize your rules
      //     minChunks: 3, //  minimum common number
      //     priority: 5,
      //     reuseExistingChunk: true
      //   }
      // }
    } : {})
  },
}
